import { defineStore } from 'pinia'
import { setUserInfo, getUserInfo, removeUserInfo } from '@/utils/storage'
import { login, info } from '@/api/login'

const useUserStore = defineStore('user', {
  state: (): UserStoreState => {
    return {
      token: getUserInfo().token || '',
      userInfo: getUserInfo().userInfo || {}
    }
  },
  getters: {
    isLogin: state => !!state.token,
    userName: state => {
      return state.userInfo.username || '-'
    }
  },
  actions: {
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
    },
    setToken(token: string) {
      this.token = token
    },
    async login(userForm: UserInfo) {
      // try {
      const { data: tokenInfo } = await login(userForm)
      this.setToken(tokenInfo.token)
      const { data: userInfo } = await info()
      this.setUserInfo(userInfo)
      // 勾选记住登录状态后，持久化存储
      if (userForm.remember) {
        setUserInfo({
          token: tokenInfo.token,
          userInfo: userInfo
        })
      } else {
        removeUserInfo()
      }
    },
    async logout() {
      // try {
      // await logout()
      // } catch (error) {}
      removeUserInfo()
      return Promise.resolve()
    }
  }
})

export { useUserStore }
